<template>
  <div class="param-item-table">
    <el-table 
      :data="params" 
      border 
      size="mini"
      class="params-table"
      :row-class-name="getRowClassName"
      :max-height="maxHeight"
      v-loading="loading"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
    >
      <!-- 参数名称 -->
      <el-table-column prop="paramName" label="参数名称" width="150" fixed>
        <template #default="scope">
          <el-input 
            v-model="scope.row.paramName" 
            size="mini" 
            placeholder="如：屈服强度-荷载"
            @blur="handleParamNameChange(scope.row)"
            maxlength="30"
            show-word-limit
          ></el-input>
        </template>
      </el-table-column>

      <!-- 参数编码 -->
      <el-table-column prop="paramCode" label="参数编码" width="120">
        <template #default="scope">
          <el-input 
            v-model="scope.row.paramCode" 
            size="mini" 
            placeholder="如：yieldLoad"
            @blur="validateParamCode(scope.row)"
            maxlength="50"
          ></el-input>
        </template>
      </el-table-column>

      <!-- 数据类型 -->
      <el-table-column prop="dataType" label="数据类型" width="120">
        <template #default="scope">
          <el-select 
            v-model="scope.row.dataType" 
            size="mini"
            @change="handleDataTypeChange(scope.row)"
          >
            <el-option label="文本" value="text"></el-option>
            <el-option label="数字" value="number"></el-option>
            <el-option label="日期" value="date"></el-option>
            <el-option label="下拉选择" value="select"></el-option>
            <el-option label="多行文本" value="textarea"></el-option>
            <el-option label="附件上传" value="attachment"></el-option>
            <el-option label="布尔值" value="boolean"></el-option>
          </el-select>
        </template>
      </el-table-column>

      <!-- 单位 -->
      <el-table-column prop="unit" label="单位" width="100">
        <template #default="scope">
          <el-select 
            v-model="scope.row.unit" 
            size="mini" 
            placeholder="选择/输入单位" 
            allow-create
            filterable
          >
            <el-option label="无" value=""></el-option>
            <el-option label="mm" value="mm"></el-option>
            <el-option label="mm²" value="mm²"></el-option>
            <el-option label="kN" value="kN"></el-option>
            <el-option label="MPa" value="MPa"></el-option>
            <el-option label="%" value="%"></el-option>
            <el-option label="kg" value="kg"></el-option>
            <el-option label="g" value="g"></el-option>
            <el-option label="m" value="m"></el-option>
            <el-option label="mm³" value="mm³"></el-option>
            <el-option label="kg/m³" value="kg/m³"></el-option>
            <el-option label="°" value="°"></el-option>
            <el-option label="N" value="N"></el-option>
            <el-option label="Pa" value="Pa"></el-option>
            <el-option label="kPa" value="kPa"></el-option>
            <el-option label="GPa" value="GPa"></el-option>
            <el-option label="s" value="s"></el-option>
            <el-option label="min" value="min"></el-option>
            <el-option label="h" value="h"></el-option>
          </el-select>
        </template>
      </el-table-column>

      <!-- 参数类型 -->
      <el-table-column prop="paramType" label="参数类型" width="140">
        <template #default="scope">
          <el-select 
            v-model="scope.row.paramType" 
            size="mini" 
            @change="handleParamTypeChange(scope.row)"
          >
            <el-option label="基础参数（手动录入）" value="base"></el-option>
            <el-option label="计算参数（自动计算）" value="calculation"></el-option>
          </el-select>
        </template>
      </el-table-column>

      <!-- 是否必填 -->
      <el-table-column prop="required" label="必填" width="80" align="center">
        <template #default="scope">
          <el-checkbox 
            v-model="scope.row.required"
            @change="handleRequiredChange(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>

      <!-- 多测次配置 -->
      <el-table-column label="多测次配置" width="190">
        <template #default="scope">
          <div class="multi-measure-config">
            <el-select 
              v-model="scope.row.multiMeasureCount" 
              size="mini"
              placeholder="测次数量"
              :disabled="scope.row.paramType === 'calculation'"
              @change="handleMultiMeasureChange(scope.row)"
            >
              <el-option label="1次（默认）" :value="1"></el-option>
              <el-option label="2次" :value="2"></el-option>
              <el-option label="3次" :value="3"></el-option>
              <el-option label="4次" :value="4"></el-option>
              <el-option label="5次" :value="5"></el-option>
              <el-option label="6次" :value="6"></el-option>
            </el-select>
            <el-checkbox 
              v-model="scope.row.isMultiMeasure" 
              :disabled="scope.row.paramType === 'calculation'"
              @change="handleMultiMeasureToggle(scope.row)"
              class="multi-measure-checkbox"
            >启用</el-checkbox>
          </div>
        </template>
      </el-table-column>

      <!-- 数字精度 -->
      <el-table-column label="数字精度" width="100">
        <template #default="scope">
          <el-input-number
            v-if="scope.row.dataType === 'number'"
            v-model="scope.row.precision"
            :min="0"
            :max="6"
            size="mini"
            controls-position="right"
            placeholder="小数位"
          ></el-input-number>
          <span v-else class="not-applicable">-</span>
        </template>
      </el-table-column>

      <!-- 列宽配置 -->
      <el-table-column label="列宽(px)" width="120">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.columnWidth"
            :min="80"
            :max="300"
            size="mini"
            controls-position="right"
          ></el-input-number>
        </template>
      </el-table-column>

      <!-- 输入提示 -->
      <el-table-column label="输入提示" width="180">
        <template #default="scope">
          <el-input 
            v-model="scope.row.placeholder"
            size="mini"
            placeholder="如：请输入检测批次"
            maxlength="50"
            show-word-limit
          ></el-input>
        </template>
      </el-table-column>

      <!-- 依赖参数 -->
      <el-table-column label="依赖参数" width="180">
        <template #default="scope">
          <el-select 
            v-if="scope.row.paramType === 'calculation'"
            v-model="scope.row.dependencies"
            multiple
            size="mini"
            placeholder="选择依赖的基础参数"
            @change="$emit('dependencies-change', scope.row)"
          >
            <el-option 
              v-for="baseParam in getBaseParams()"
              :key="baseParam.paramCode"
              :label="`${baseParam.paramName}（${baseParam.paramCode}）`"
              :value="baseParam.paramCode"
            ></el-option>
          </el-select>
          <span v-else class="not-applicable">-</span>
        </template>
      </el-table-column>

      <!-- 计算规则 -->
      <el-table-column label="计算规则" width="200">
        <template #default="scope">
          <el-button 
            v-if="scope.row.paramType === 'calculation'"
            type="text" 
            size="mini"
            @click="$emit('open-calc-dialog', scope.row, groupIndex, childIndex, isNested)"
            :class="['calc-rule-btn', { 'empty': !scope.row.calculationExpr }]"
          >
            {{ scope.row.calculationExpr ? formatCalcExpr(scope.row.calculationExpr) : '点击配置计算规则' }}
          </el-button>
          <span v-else class="not-applicable">-</span>
        </template>
      </el-table-column>

      <!-- 下拉选项 -->
      <el-table-column label="下拉选项" width="100">
        <template #default="scope">
          <el-button 
            v-if="scope.row.dataType === 'select'"
            type="text" 
            size="mini"
            @click="$emit('open-select-dialog', scope.row)"
            :class="{ 'configured': scope.row.options && scope.row.options.length }"
          >
            {{ scope.row.options && scope.row.options.length ? `已配置(${scope.row.options.length})` : '配置选项' }}
          </el-button>
          <span v-else class="not-applicable">-</span>
        </template>
      </el-table-column>

      <!-- 校验规则 -->
      <el-table-column label="校验规则" width="100">
        <template #default="scope">
          <el-button 
            type="text" 
            size="mini"
            @click="$emit('open-validate-dialog', scope.row)"
            :class="{ 'configured': hasValidationRules(scope.row) }"
          >
            {{ hasValidationRules(scope.row) ? '已配置' : '配置校验' }}
          </el-button>
        </template>
      </el-table-column>

      <!-- 条件显示 -->
      <el-table-column label="条件显示" width="100">
        <template #default="scope">
          <el-button 
            type="text" 
            size="mini"
            @click="$emit('open-condition-dialog', scope.row)"
            :class="{ 'configured': hasConditionRules(scope.row) }"
          >
            {{ hasConditionRules(scope.row) ? '已配置' : '配置显示' }}
          </el-button>
        </template>
      </el-table-column>

      <!-- 排序 -->
      <el-table-column label="排序" width="100">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.sortOrder"
            :min="1"
            :max="1000"
            size="mini"
            controls-position="right"
          ></el-input-number>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="80" fixed="right">
        <template #default="scope">
          <el-button 
            type="danger" 
            icon="el-icon-delete" 
            size="mini"
            @click="$emit('remove-param', groupIndex, childIndex, isNested, scope.$index)"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="params.length === 0" class="empty-params">
      <i class="el-icon-document"></i>
      <p>暂无参数，点击"添加参数"按钮开始配置</p>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui';

export default {
  name: 'ParamItemTable',
  props: {
    params: {
      type: Array,
      default: () => []
    },
    groupIndex: {
      type: Number,
      required: true
    },
    childIndex: {
      type: Number,
      default: -1
    },
    isNested: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    maxHeight: {
      type: Number,
      default: 400
    }
  },
  data() {
    return {
      baseParams: [] // 当前组的基础参数缓存
    };
  },
  watch: {
    params: {
      handler() {
        this.updateBaseParams();
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * 获取行样式类名
     */
    getRowClassName({ row }) {
      if (row.paramType === 'calculation') {
        return 'calculation-param-row';
      }
      return '';
    },

    /**
     * 参数名称变更处理
     */
    handleParamNameChange(param) {
      if (!param.paramName.trim()) {
        Message.warning('参数名称不能为空');
        param.paramName = '新参数';
      }
    },

    /**
     * 验证参数编码
     */
    validateParamCode(param) {
      if (!param.paramCode.trim()) {
        Message.warning('参数编码不能为空');
        return false;
      }

      // 检查编码格式（字母、数字、下划线）
      const codeRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
      if (!codeRegex.test(param.paramCode)) {
        Message.warning('参数编码只能包含字母、数字和下划线，且不能以数字开头');
        return false;
      }

      return true;
    },

    /**
     * 数据类型变更处理
     */
    handleDataTypeChange(param) {
      // 初始化默认配置
      switch (param.dataType) {
        case 'number':
          if (param.precision === undefined) param.precision = 1;
          break;
        case 'select':
          if (!param.options) param.options = [];
          break;
        case 'attachment':
          if (!param.attachmentConfig) {
            param.attachmentConfig = {
              multiple: false,
              fileTypes: ['jpg', 'png', 'pdf', 'docx'],
              maxSize: 10
            };
          }
          break;
      }

      // 计算参数必须是数字类型或文本类型
      if (param.paramType === 'calculation' && param.dataType !== 'number' && param.dataType !== 'text') {
         param.dataType = 'text';
         Message.warning('计算参数的数据类型必须为数字或文本');
      }
    },

    /**
     * 参数类型变更处理
     */
    handleParamTypeChange(param) {
      if (param.paramType === 'calculation') {
        // 切换为计算参数时自动设置数据类型为数字
        param.dataType = 'number';
        param.isMultiMeasure = false; // 计算参数不支持多测次
        
        // 触发打开计算规则对话框
        this.$emit('open-calc-dialog', param, this.groupIndex, this.childIndex, this.isNested);
      } else {
        // 切换为基础参数时清空计算相关配置
        param.calculationExpr = '';
        param.dependencies = [];
      }
    },

    /**
     * 必填项变更处理
     */
    handleRequiredChange(param) {
      if (param.required && !param.validateRule) {
        param.validateRule = { required: true };
      }
    },

    /**
     * 多测次数量变更处理
     */
    handleMultiMeasureChange(param) {
      if (param.multiMeasureCount > 1) {
        param.isMultiMeasure = true;
      } else {
        param.isMultiMeasure = false;
      }
    },

    /**
     * 多测次开关变更处理
     */
    handleMultiMeasureToggle(param) {
      if (!param.isMultiMeasure) {
        param.multiMeasureCount = 1;
      } else if (param.multiMeasureCount === 1) {
        param.multiMeasureCount = 3; // 默认3次
      }
    },

    /**
     * 获取基础参数列表
     */
    getBaseParams() {
      return this.baseParams;
    },

    /**
     * 更新基础参数缓存
     */
    updateBaseParams() {
      this.baseParams = this.params.filter(param => param.paramType === 'base');
    },

    /**
     * 格式化计算表达式显示
     */
    formatCalcExpr(expr) {
      if (expr.length > 25) {
        return `${expr.substring(0, 25)}...`;
      }
      return expr;
    },

    /**
     * 检查是否有验证规则
     */
    hasValidationRules(param) {
      return param.validateRule && Object.keys(param.validateRule).length > 0;
    },

    /**
     * 检查是否有条件显示规则
     */
    hasConditionRules(param) {
      return param.conditionShow && Object.keys(param.conditionShow).length > 0;
    }
  }
};
</script>

<style scoped>
.param-item-table {
  width: 100%;
}

.params-table {
  width: 100%;
  font-size: 12px;
}

.params-table ::v-deep .calculation-param-row {
  background-color: #f0f9ff;
}

.params-table ::v-deep .calculation-param-row:hover > td {
  background-color: #e6f7ff !important;
}

.multi-measure-config {
  display: flex;
  flex-direction: row;
  gap: 5px;
}

.multi-measure-checkbox {
  margin-left: 0;
}

.calc-rule-btn {
  color: #409eff;
  text-align: left;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.calc-rule-btn.empty {
  color: #909399;
  font-style: italic;
}

.not-applicable {
  color: #c0c4cc;
  font-style: italic;
}

.configured {
  color: #67c23a;
}

.empty-params {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  background-color: #fafafa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

.empty-params i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-params p {
  margin: 0;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 1600px) {
  .params-table {
    font-size: 11px;
  }
}
</style>